package com.kakaxi.mybilibili.base;

import android.app.Application;

import com.kakaxi.mybilibili.bean.MemberBean;
import com.kakaxi.mybilibili.net.HttpClientHelper;
import com.kakaxi.mybilibili.net.Netroid;
import com.kakaxi.mybilibili.utils.ActivityStackManager;
import com.kakaxi.mybilibili.utils.SharedPreferencesUtil;

import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.cookie.BasicClientCookie2;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义应用管理器
 * Created by kakaxi on 16/8/2.
 */
public class MyApplication extends Application implements Thread.UncaughtExceptionHandler {

    /** 用户信息文件名 **/
    public static final String PREFERENCE_NAME_USER_INFO = "userInfo";
    /** 用户id键 **/
    public static final String PREFERENCE_KEY_USER_ID = "userId";
    /** 用户名键 **/
    public static final String PREFERENCES_KEY_USERNAME = "username";
    /** 用户头像键 **/
    public static final String PREFERENCES_KEY_USER_FACE = "userFace";

    /** 用户cookie信息文件名 **/
    public static final String PREFERENCE_NAME_USER_COOKIE = "userCookie";

    /** 共享数据的集合 **/
    private Map<String, Object> mShareDataMap;

    /** 用户信息类 **/
    private MemberBean mMemberBean;

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化网络请求控件
        Netroid.init(getApplicationContext());
        // 初始化共享数据集合
        mShareDataMap = new HashMap<>();
        // 全部出错捕捉
//        Thread.setDefaultUncaughtExceptionHandler(this);

        // 读取用户信息
        loadMemberInfo();
        // 读取用户cookie
        loadUserCookie();
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        ActivityStackManager.getInstance().popAllActivity();
        System.exit(0);
    }

    /**
     * 放入分享数据
     *
     * @param key   键
     * @param value 值
     */
    public void putShareData(String key, Object value) {
        if (mShareDataMap != null) {
            mShareDataMap.put(key, value);
        }
    }

    /**
     * 取出分享数据
     *
     * @param key 键
     * @return 值
     */
    public Object getShareData(String key) {
        if (mShareDataMap != null) {
            return mShareDataMap.get(key);
        }
        return null;
    }

    /**
     * 设置用户信息类
     *
     * @param memberBean 用户信息类
     */
    public void setMemberBean(MemberBean memberBean) {
        mMemberBean = memberBean;
        saveMemberInfo();
    }

    /**
     * 获取用户信息类
     *
     * @return 用户信息类
     */
    public MemberBean getMemberBean() {
        return mMemberBean;
    }

    /**
     * 保存用户信息
     */
    private void saveMemberInfo() {
        SharedPreferencesUtil.writeXML(getBaseContext(), PREFERENCE_NAME_USER_INFO,
                PREFERENCE_KEY_USER_ID, mMemberBean.getMid());
        SharedPreferencesUtil.writeXML(getBaseContext(), PREFERENCE_NAME_USER_INFO,
                PREFERENCES_KEY_USERNAME, mMemberBean.getName());
        SharedPreferencesUtil.writeXML(getBaseContext(), PREFERENCE_NAME_USER_INFO,
                PREFERENCES_KEY_USER_FACE, mMemberBean.getFace());
    }

    /**
     * 读取用户信息
     */
    private void loadMemberInfo() {
        String userId = SharedPreferencesUtil.readXML(getBaseContext(),
                PREFERENCE_NAME_USER_INFO, PREFERENCE_KEY_USER_ID);
        if (userId != null) {
            String username = SharedPreferencesUtil.readXML(getBaseContext(),
                    PREFERENCE_NAME_USER_INFO, PREFERENCES_KEY_USERNAME);
            String userFace = SharedPreferencesUtil.readXML(getBaseContext(),
                    PREFERENCE_NAME_USER_INFO, PREFERENCES_KEY_USER_FACE);
            mMemberBean = new MemberBean();
            mMemberBean.setMid(userId);
            mMemberBean.setName(username);
            mMemberBean.setFace(userFace);
        }
    }


    /**
     * 保存用户cookie信息
     *
     * @param cookieHeaders cookie数组
     */
    public void saveUserCookie(Header[] cookieHeaders) {
        for (Header header : cookieHeaders) {
            SharedPreferencesUtil.writeXML(getBaseContext(), PREFERENCE_NAME_USER_COOKIE, header
                    .getName(), header.getValue());
        }
    }

    /**
     * 保存用户cookie信息
     *
     * @param cookieMap cookie集合
     */
    public void saveUserCookie(Map<String, String> cookieMap) {
        for (String key : cookieMap.keySet()) {
            SharedPreferencesUtil.writeXML(getBaseContext(), PREFERENCE_NAME_USER_COOKIE, key,
                    cookieMap.get(key));
        }
    }

    /**
     * 读取cookie, 并设置好cookie
     */
    public void loadUserCookie() {
        Map<String, ?> cookieMap = SharedPreferencesUtil.getAll(getBaseContext(),
                PREFERENCE_NAME_USER_COOKIE);
        if (cookieMap != null && cookieMap.size() != 0) {
            HttpClient httpClient = HttpClientHelper.getInstance();
            for (String key : cookieMap.keySet()) {
                // 给浏览器添加用户的cookie信息
                HttpClientHelper.addCookie(httpClient, new BasicClientCookie2(key, cookieMap.get
                        (key).toString()));
            }
        }
    }


}
